package com.wulab.backend.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wulab.backend.entity.GeneInfo;
import com.wulab.backend.utils.Option;
import com.wulab.backend.mapper.GeneInfoMapper;
import com.wulab.backend.service.GeneInfoService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.wulab.backend.utils.ExcelUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;


@Service
public class GeneInfoServiceImpl extends ServiceImpl<GeneInfoMapper, GeneInfo> implements GeneInfoService {

    @Autowired
    private GeneInfoMapper geneInfoMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)  // 使方法具备事务管理，发生任何Exception及其子类都会回滚
    public void importGeneInfo(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        // 文件内容处理
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0);  // 获取第一个工作表
        ExcelUtils excelUtils = new ExcelUtils();

        Iterator<Row> rows = sheet.iterator();
        List<GeneInfo> geneInfoList = new ArrayList<>();

        for (int i = 1; i <= sheet.getPhysicalNumberOfRows(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;
            GeneInfo geneInfo = new GeneInfo();
            geneInfo.setGene(excelUtils.getStringCellValue(row, 0));
            geneInfo.setLoopid(excelUtils.getStringCellValue(row, 1));
            geneInfo.setBin1(excelUtils.getStringCellValue(row, 2));
            geneInfo.setBin2(excelUtils.getStringCellValue(row, 3));
            geneInfo.setEe(excelUtils.getIntCellValue(row, 4));
            geneInfo.setEp(excelUtils.getIntCellValue(row, 5));
            geneInfo.setPp(excelUtils.getIntCellValue(row, 6));
            geneInfo.setOther(excelUtils.getIntCellValue(row, 7));
            geneInfo.setBinInfo1(excelUtils.getStringCellValue(row, 8));
            geneInfo.setBinInfo2(excelUtils.getStringCellValue(row, 9));
            geneInfo.setRNAexp(excelUtils.getDoubleCellValue(row, 10));
            geneInfo.setWeighs(excelUtils.getIntCellValue(row, 11));
            String[] rangeParts = excelUtils.getStringCellValue(row, 1).split("_");
            String[] part1 = rangeParts[0].split(":");
            geneInfo.setChrom(part1[0]);
            String[] range1 = part1[1].split("-");
            geneInfo.setRangeStart1(Long.valueOf(range1[0]));
            geneInfo.setRangeEnd1(Long.valueOf(range1[1]));

            String[] part2 = rangeParts[1].split(":");
            String[] range2 = part2[1].split("-");
            geneInfo.setRangeStart2(Long.valueOf(range2[0]));
            geneInfo.setRangeEnd2(Long.valueOf(range2[1]));

            // 添加到集合中
            geneInfoList.add(geneInfo);
        }

        // 批量保存数据到数据库
        saveBatch(geneInfoList);
    }

    public Map<String, Object> getGeneInfo(int pageNum, int pageSize, Map<String, String> searchParams) {
        // 创建分页对象，pageNum 为页码，pageSize 为每页条数

        Page<GeneInfo> page = new Page<>(pageNum, pageSize);

        QueryWrapper<GeneInfo> queryWrapper;

        if (searchParams !=null && !searchParams.isEmpty()) {
            queryWrapper = new QueryWrapper<>();
            String gene = searchParams.get("gene");
            if (gene != null) {
                queryWrapper.eq("gene", gene);
            } else {
                String chrom = searchParams.get("chrom");
                long rangeStart = Long.parseLong(searchParams.get("rangeStart"));
                long rangeEnd = Long.parseLong(searchParams.get("rangeEnd"));
                if (chrom != null && !chrom.trim().isEmpty()) {
                    queryWrapper.eq("chrom", chrom);  // 添加 chrom 精确匹配条件
                }

                // 添加 range 条件，检查范围是否在两个区间中的任何一个范围内
                if (rangeStart > 0 && rangeEnd > 0) {
                    // 检查是否在第一个区间
                    queryWrapper.and(wrapper ->
                                    wrapper.le("range_start1", rangeStart) // rangeStart1 <= rangeStart
                                            .ge("range_end1", rangeEnd)     // rangeEnd1 >= rangeEnd
                            )
                            .or(wrapper ->
                                    // 检查是否在第二个区间
                                    wrapper.le("range_start2", rangeStart) // rangeStart2 <= rangeStart
                                            .ge("range_end2", rangeEnd)     // rangeEnd2 >= rangeEnd
                            );
                }
            }
        } else {
            queryWrapper = null;
        }


        // 调用 selectPage 方法进行分页查询
        IPage<GeneInfo> geneInfoPage = geneInfoMapper.selectPage(page, queryWrapper);

        Map<String, Object> result = new HashMap();
        result.put("data", geneInfoPage.getRecords());
        result.put("total", geneInfoPage.getTotal());
        // 返回分页结果中的记录列表
        return result;
    }

    public List<Option> getOptions(String column) {
        List<Option> options = new ArrayList<>();
        QueryWrapper<GeneInfo> queryWrapper = new QueryWrapper<>();
        String sql = "DISTINCT " + column;
        queryWrapper.select(sql).isNotNull(column);
        List<GeneInfo> entities = geneInfoMapper.selectList(queryWrapper);
        for (GeneInfo entity : entities) {
            String label = getColumnValue(entity, column);  // 根据 column 获取对应的字段值
            Option option = new Option(label, label);  // 假设 'label' 和 'value' 是相同的
            options.add(option);
        }
        return options;
    }

    private String getColumnValue(GeneInfo entity, String column) {
        switch (column.toLowerCase()) {
            case "gene":
                return entity.getGene();  // 返回 'name' 字段的值
            case "loopid":
                return entity.getLoopid();  // 返回 'category' 字段的值
            // 其他列的处理
            case "chrom":
                return entity.getChrom();  // 返回 'category' 字段的值
            default:
                return "";
        }
    }
}
